﻿// Gateway.Api 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using System.Text.Json;
using Aurora.AI.Abstractions;
using Aurora.AI.Domain.Domain.ChatChannel.Repositories;
using Aurora.AI.Gateway.Models.ChatChannel;
using Mapster;

namespace Aurora.AI.Gateway.Services.ChatChannel;

public class ChatChannelService(IChatChannelRepository chatChannelRepository)
{
    /// <summary>
    /// 获取配置了 自动监控的渠道列表
    /// </summary>
    /// <returns></returns>
    public async Task<List<Domain.Domain.ChatChannel.Aggregates.ChatChannel>> GetListWithControlAutomatically()
    {
        return await chatChannelRepository.GetListAsync(x => x.ControlAutomatically && !x.Disable);
    }

    /// <summary>
    /// 更新响应时间
    /// </summary>
    /// <param name="id"></param>
    /// <param name="milliseconds"></param>
    /// <returns></returns>
    public async Task<bool> UpdateResponseTime(string id, long milliseconds)
    {
        await chatChannelRepository.GetDb().Updateable<Domain.Domain.ChatChannel.Aggregates.ChatChannel>()
            .SetColumns(x => x.ResponseTime == milliseconds)
            .Where(x => x.Id.Equals(id))
            .ExecuteCommandAsync();
        return true;
    }

    public async Task<AI.Domain.Domain.ChatChannel.Aggregates.ChatChannel> GetById(string id)
    {
        return await chatChannelRepository.GetByIdAsync(id);
    }

    public async Task<IEnumerable<AI.Domain.Domain.ChatChannel.Aggregates.ChatChannel>> GetByModel(string model)
    {
        return await chatChannelRepository.GetByModelAsync(model);
    }


    /// <summary>
    /// 获取包含指定模型名的渠道列表 如果缓存中有则从缓存中获取
    /// </summary>
    /// <param name="model">模型名</param>
    /// <returns></returns>
    public async ValueTask<IEnumerable<AI.Domain.Domain.ChatChannel.Aggregates.ChatChannel>>
        GetChannelsContainsModelAsync(string model)
    {
        var data = await chatChannelRepository.GetListAsync();
        return (data.Where(x => x.Models.Contains(model)));
    }

    /// <summary>
    /// 获取分页列表
    /// </summary>
    /// <param name="page"></param>
    /// <param name="size"></param>
    /// <returns></returns>
    public async Task<(int total, List<ChatChannelPageListResponse>)> GetPageListAsync(int page, int size)
    {
        List<ChatChannelPageListResponse> result = new List<ChatChannelPageListResponse>();
        (int total, List<Domain.Domain.ChatChannel.Aggregates.ChatChannel> list) =
            await chatChannelRepository.GetPageListAsync(page, size);
        if (list.Count == 0)
            return (total, result);
        var aiTypeModels = AuroraAIGlobal.PlatformNames;
        result = list.Adapt<List<ChatChannelPageListResponse>>();
        foreach (var chatChannel in result)
        {
            var typeName = aiTypeModels.FirstOrDefault(x => x.Value.Equals(chatChannel.Type));
            chatChannel.TypeName = typeName.Key;
        }
        return (total, result);
    }


    public async Task<bool> CreateAsync(ChatChannelCreateRequest request)
    {
        var entity = new Domain.Domain.ChatChannel.Aggregates.ChatChannel()
        {
            CreationTime = DateTime.Now,
            ModificationTime = DateTime.Now,
            Modifier = request.OperatorId,
            Creator = request.OperatorId,
            Address = request.Address,
            ControlAutomatically = false,
            Disable = false,
            Extension = "",
            IsDeleted = false,
            Models = JsonSerializer.Serialize(request.ModelList),
            Other = "",
            Order = 1,
            Type = request.Type,
            Key = request.Key,
            Name = request.Name
        };
        await chatChannelRepository.Create(entity);
        return true;
    }


    public async Task<bool> UpdateAsync(ChatChannelUpdateRequest request)
    {
        var entity = await chatChannelRepository.GetByIdAsync(request.Id);
        if (entity == null)
        {
            throw new ArgumentException("未找到渠道");
        }

        entity.Address = request.Address;
        entity.ModificationTime = DateTime.Now;
        entity.Modifier = request.OperatorId;
        entity.Models = JsonSerializer.Serialize(request.ModelList);
        entity.Type = request.Type;
        entity.Key = request.Key;
        entity.Name = request.Name;
        await chatChannelRepository.UpdateChannel(entity);
        return true;
    }


    public async Task<bool> UpdateDisable(ChannelStatusUpdateRequest request)
    {
        var entity = await chatChannelRepository.GetByIdAsync(request.Id);
        if (entity == null)
        {
            throw new ArgumentException("未找到渠道");
        }

        entity.Disable = request.Status;
        entity.ModificationTime = DateTime.Now;
        entity.Modifier = request.OperatorId;
        await chatChannelRepository.UpdateChannel(entity);
        return true;
    }

    public async Task<bool> UpdateOrder(string id, int order)
    {
        await chatChannelRepository.GetDb().Updateable<Domain.Domain.ChatChannel.Aggregates.ChatChannel>()
            .SetColumns(x => x.Order == order)
            .Where(x => x.Id.Equals(id))
            .ExecuteCommandAsync();
        return true;
    }

    public async Task<bool> UpdateControlAutomatically(ChannelStatusUpdateRequest request)
    {
        var entity = await chatChannelRepository.GetByIdAsync(request.Id);
        if (entity == null)
        {
            throw new ArgumentException("未找到渠道");
        }

        entity.ControlAutomatically = request.Status;
        entity.ModificationTime = DateTime.Now;
        entity.Modifier = request.OperatorId;
        await chatChannelRepository.UpdateChannel(entity);
        return true;
    }


    public async Task<bool> RemoveAsync(string id)
    {
        return await chatChannelRepository.DeleteAsync(id);
    }
}